<template>
  <div>
    <!-- 面包屑导航   -->

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <!-- 添加角色 -->
      <el-button type="primary"
@click="addRolesDialog = true">添加角色</el-button>

      <el-table :data="rolesData"
          style="width:100%"
          stripe
          border>
        <!-- 下拉展示权限 -->
        <el-table-column type="expand">
            <template slot-scope="scope">
                <el-row  class="vcenter"
                    colspan='5'
                    v-for="(item, index) in scope.row.children"
                    :key="index"
                    :class="['bdbottom',index === 0 ? 'bdtop':'']">
                    <el-col :span="5"  >
                        <el-tag closable
                            @close="deleteTag(item,scope.row)"
                            disable-transitions>{{item.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span='19' >
                        <el-row  class="vcenter"
                              v-for="(item2, index2) in item.children"
                              :key="index2"
                              :class="[index2 === 0 ? '':'bdtop']">
                                                          <el-col :span="6">
                                                              <el-tag closable
                              type="success"
                              @close="deleteTag(item2,scope.row)"
                              disable-transitions>{{item2.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="18">
                                <el-tag v-for="(item3, index3) in item2.children"
                                    :key="index3"
                                    closable
                                    type="warning"
                                    @close="deleteTag(item3,scope.row)"
                                    disable-transitions>{{item3.authName}}</el-tag>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="70px"></el-table-column>
        <el-table-column prop="roleName"
label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc"
label="角色描述"></el-table-column>
        <el-table-column label="操作">
            <template slot-scope='scope'>
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="changeUser(scope.row)">编辑</el-button>
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="deleteUser(scope.row)">删除</el-button>
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="settingUser(scope.row)">分配权限</el-button>
            </template>
        </el-table-column>
      </el-table>
        <!-- 编辑用户信息 -->
        <el-dialog
            title="修改用户信息"
            :visible.sync="changeUserDialog"
            width="50%">
            <el-form ref='changeUserRef'
:model='changeUserFrom'
label-width="100px"
:rules="addRolesRules">
                <el-form-item label="角色名称"
prop="roleName">
                    <el-input v-model="changeUserFrom.roleName" ></el-input>
                </el-form-item>
                <el-form-item label="角色描述"
prop="roleDesc">
                    <el-input v-model="changeUserFrom.roleDesc" ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer"
class="dialog-footer">
                <el-button @click="changeUserDialog = false">取 消</el-button>
                <el-button type="primary"
@click="changeUserEnter">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesDialog"
        width="50%"
        @close="closeAddRolesDialog">
        <el-form
          ref="addRolesRef"
          :model="addRolesForm"
          :rules="addRolesRules"
          label-width="100px">
          <el-form-item label="角色名称"
prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述"
prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
class="dialog-footer">
          <el-button @click="addRolesDialog = false">取 消</el-button>
          <el-button type="primary"
@click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="分配权限"
        :visible.sync="changeRolesDialog"
        width="50%"
        @close="closeRolesDialog">
        <el-tree :data="changeRolesList"
        default-expand-all
        :props="rolesListProps"
        :default-checked-keys="checkedRolesList"
        node-key="id"
        show-checkbox
        :current-node-key='chooseNode'
        ref="treeRef">
        </el-tree>
        <span slot="footer"
class="dialog-footer">
          <el-button @click="closeRolesDialog">取 消</el-button>
          <el-button type="primary"
@click="changeRoles">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesData: [],
      addRolesDialog: false,
      changeUserDialog: false,
      addRolesForm: {},
      changeUserFrom: {},
      changeRolesDialog: false,
      changeRolesList: {},
      checkedRolesList: [],
      chooseNode: '',
      rolesListProps: {
        children: 'children',
        label: 'authName'
      },
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 5,
            max: 12,
            message: '长度在 5 到 12 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.message.error('获取角色列表失败') }
      this.rolesData = res.data
    },
    closeAddRolesDialog() {
      this.$refs.addRolesRef.resetFields()
    },
    addRoles() {
      this.$refs.addRolesRef.validate(async(valid) => {
        if (valid) {
          const { data: res } = await this.$http.post(
            'roles',
            this.addRolesForm
          )
          if (res.meta.status !== 201) {
            return this.$message.error('添加角色失败')
          } else {
            console.log(res)
          }
          this.addRolesDialog = false
          this.$message({
            message: '添加角色成功',
            type: 'success'
          })
          this.getRolesList()
        } else {
          console.log('添加角色失败')
          return false
        }
      })
    },
    async changeUser(userInfo) {
      const { data: res } = await this.$http.get(`roles/${userInfo.id}`)
      if (res.meta.status !== 200) { return this.$message.error('获取用户信息失败') }
      this.changeUserFrom = res.data
      this.changeUserDialog = true
    },
    changeUserEnter() {
      this.$refs.changeUserRef.validate(async(valid) => {
        if (!valid) return this.$message.error('修改用户失败')
        await this.$http.put(
          `roles/${this.changeUserFrom.roleId}`,
          this.changeUserFrom
        )
        this.changeUserDialog = false
        this.getRolesList()
        this.$message({
          message: '修改用户信息成功',
          type: 'success'
        })
      })
    },
    deleteUser(userInfo) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete(`roles/${userInfo.id}`)
          if (res.meta.status === 200) {
            this.getRolesList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteTag(rolesInfo, userInfo) {
      this.$confirm('是否删除权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete(
            `roles/${userInfo.id}/rights/${rolesInfo.id}`
          )
          if (res.meta.status === 200) {
            rolesInfo.children = res.data
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            userInfo.children = res.data
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async settingUser(rolesInfo) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) { return this.$message.error('获取用户权限失败') }
      this.changeRolesList = res.data
      this.getLeaKeys(rolesInfo, this.checkedRolesList)

      this.changeRolesDialog = true
    },
    // 递归获取已经授权的列表
    getLeaKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeaKeys(item, arr)
      })
    },
    closeRolesDialog() {
      this.checkedRolesList = []
      this.changeRolesDialog = false
    },
    async changeRoles() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      this.chooseNode = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.chooseNode}/rights`
      )
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.changeRolesDialog = false
    }
  }
}
</script>
<style lang="less">
.el-card {
  margin: 20px 0;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  flex-direction: row;
  align-items: center;
}
.rolesDataWrap {
  margin: 20px 25px;
}
</style>
